<template>
  <div class="app-container">

    <vxe-grid
      ref="xGrid"
      border
      resizable
      keep-source
      size="small"
      align="center"
      round
      highlight-hover-row
      :loading="loading"
      :pager-config="tablePage"
      :columns="tableColumn"
      :data="tableData"
      :form-config="tableForm"
      :toolbar="{slots: {buttons: 'toolbar_buttons'}}"
      @page-change="page"
      @form-submit="search"
    >
      <template v-slot:operate="{ row }">
        <vxe-button v-has="perms.edit" type="text" circle @click="edit(row)"><svg-icon icon-class="bianji" /></vxe-button>
        <vxe-button v-if="isNotSelf(row)" v-has="perms.delete" status="danger" title="删除" type="text" @click="remove(row)"><svg-icon icon-class="shanchu" /></vxe-button>
        <vxe-button v-has="perms.delete" status="danger" title="删除" type="text" @click="resetPassword(row)"><svg-icon icon-class="zhongzhimima" /></vxe-button>
      </template>

      <template v-slot:toolbar_buttons>
        <vxe-button v-has="perms.add" size="mini" status="primary" icon="fa fa-plus" @click="add">新增</vxe-button>
      </template>
    </vxe-grid>

    <vxe-modal v-model="dialogVisible" :title="dialogTitle" width="800" :loading="submitLoading" resize destroy-on-close>
      <template v-slot>

        <ele-form
          ref="eleForm"
          v-model="formData"
          :form-desc="formDesc"
          :request-fn="handleSubmit"
          :rules="rules"
          label-position="right"
          :is-dialog="true"
          @close="closeDialog()"
        />
      </template>
    </vxe-modal>

    <vxe-modal v-model="resetPasswordDialogVisible" title="重置密码" width="400" :loading="resetSubmitLoading" resize destroy-on-close>
      <template v-slot>

        <ele-form
          ref="resetEleForm"
          v-model="resetFormData"
          :form-desc="resetFormDesc"
          :request-fn="resetPasswordSubmit"
          :rules="resetRules"
          label-position="right"
          :is-dialog="true"
          @close="resetCloseDialog()"
        >

          <!-- 插槽内容有el-form-item组件包裹 -->
          <span class="resetTips">{{ resetTips }}</span>

        </ele-form>
      </template>
    </vxe-modal>
  </div>
</template>
<script>
import api from '@/api/sys-user'
import strings from '@/utils/strings'
import store from '@/store'
// import elDragDialog from '@/directive/el-drag-dialog'
import { phone, email } from '@/utils/validator'
import { getToken } from '@/utils/auth'
import { config } from '@/utils/config'
import { mappingArray } from '@/utils/tools'
import roleApi from '@/api/role'

export default {
  name: '',
  components: {},
  // directives: { elDragDialog },
  props: {},
  data() {
    return {
      loading: false,
      dialogVisible: false,
      dialogTitle: '',
      name: '用户',
      submitLoading: false,
      resetPasswordDialogVisible: false,
      resetSubmitLoading: false,
      resetTips: '',
      tableData: [],
      perms: {
        add: 'sysUser:add',
        edit: 'sysUser:edit',
        delete: 'sysUser:delete'
      },
      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 10
      },
      tableForm: {
        data: {
          userName: '',
          loginName: '',
          status: '',
          phoneNumber: '',
          email: '',
          sex: ''
        },
        items: [
          { field: 'userName', title: '用户名:', itemRender: { name: '$input', props: { placeholder: '请输入', clearable: true }}},
          { field: 'loginName', title: '登录名:', itemRender: { name: '$input', props: { placeholder: '请输入', clearable: true }}},
          { field: 'status', title: '状态:', itemRender: { name: '$select', options: [], props: { placeholder: '请选择', clearable: true }}},
          { field: 'sex', title: '性别:', itemRender: { name: '$select', options: [], props: { placeholder: '请选择', clearable: true }}},
          { field: 'phoneNumber', title: '手机号:', itemRender: { name: '$input', props: { placeholder: '请输入', clearable: true }}},
          { field: 'email', title: '邮箱:', itemRender: { name: '$input', props: { placeholder: '请输入', clearable: true }}},
          { itemRender: { name: '$buttons', children: [{ props: { type: 'submit', content: '查询', status: 'primary' }}, { props: { type: 'reset', content: '重置' }}] }}

        ]
      },
      tableColumn: [
        { type: 'seq', width: 40 },
        { field: 'userName', title: '用户名' },
        { field: 'loginName', title: '登录名' },
        { field: 'statusValue', title: '状态' },
        { field: 'sexValue', title: '性别' },
        { field: 'phoneNumber', title: '手机号' },
        { field: 'email', title: '邮箱' },
        { title: '操作', width: 180, fixed: 'right', slots: { default: 'operate' }}
      ],
      formData: {
        avatar: '',
        loginName: '',
        userName: '',
        password: '',
        sex: '',
        status: '',
        phoneNumber: '',
        email: '',
        roleIds: '',
        edit: false
      },
      formDesc: {
        avatar: {
          type: 'image-uploader',
          label: '图片',
          multiple: true,
          attrs: {
            fileSize: 5,
            size: 80,
            action: config.uploadUrl,
            fileType: ['png', 'jpg', 'jpeg'],
            headers: {
              token: getToken()
            },
            responseFn(response, file) {
              return response.data.url
            }
          }
        },
        loginName: {
          type: 'input',
          label: '登录名',
          vif(row) {
            return !row.edit
          }
        },
        userName: {
          type: 'input',
          label: '用户名'
        },
        password: {
          type: 'password',
          label: '密码',
          vif(row) {
            return !row.edit
          }
        },
        sex: {
          type: 'radio',
          label: '性别',
          options: []
        },
        status: {
          type: 'radio',
          label: '状态',
          default: 0,
          options: []
        },
        phoneNumber: {
          type: 'input',
          label: '手机号'
        },
        email: {
          type: 'input',
          label: '邮箱'
        },
        roleIds: {
          type: 'select',
          label: '用户角色',
          options: [],
          attrs: {
            multiple: true,
            clearable: true,
            searchable: true
          }
        }
      },
      rules: {
        loginName: [
          { required: true, message: '登录名不能为空' },
          { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空' },
          { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '用户名不能为空' }
        ],
        phoneNumber: [{ required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: phone, trigger: 'blur' }],
        email: [{ required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: email, trigger: 'blur' }],
        userType: [{ required: true, message: '请选择用户类型', trigger: 'blur' }]
      },
      resetFormData: {
        password: ''
      },
      resetFormDesc: {
        password: {
          type: 'password',
          label: '密码'
        }
      },
      resetRules: {
        password: [
          { required: true, message: '密码不能为空' },
          { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
  },
  created() {
    this.listData()
    this.setUserStatus()
    this.setSex()
    this.getRoles()
  },
  methods: {
    listData() {
      this.loading = true
      this.tableForm.data.page = this.tablePage.currentPage
      this.tableForm.data.pageSize = this.tablePage.pageSize
      api.pageData(this.tableForm.data).then(res => {
        const data = res.data
        this.tableData = data.data
        this.tablePage.currentPage = parseInt(data.page)
        this.tablePage.pageSize = parseInt(data.pageSize)
        this.tablePage.total = parseInt(data.total)
        this.loading = false
      })
    },
    search() {
      this.tablePage.currentPage = 1
      this.listData()
    },
    page({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
      this.listData()
    },
    remove(row) {
      this.$confirm(strings.delMsg, strings.prompt, {
        confirmButtonText: strings.ok,
        cancelButtonText: strings.cancel,
        type: 'warning'
      }).then(() => {
        this.loading = true
        api.remove(row.id).then(res => {
          this.listData()
        }, () => {
          this.loading = false
        })
      })
    },
    isNotSelf(row) {
      return row.id !== store.getters.userId
    },
    add() {
      this.formData = {}
      this.formData.edit = false
      this.resetForm()
      this.dialogVisible = true
      this.dialogTitle = '新增' + this.name
    },
    edit(row) {
      this.resetForm()
      this.dialogTitle = '编辑' + this.name
      api.data(row.id).then(res => {
        this.formData = res.data
        this.formData.edit = true
        this.dialogVisible = true
      })
    },
    closeDialog() {
      this.dialogVisible = false
      this.formData = {}
    },
    resetForm() {
      if (this.$refs.eleForm) {
        this.$refs.eleForm.resetForm()
      }
    },
    handleSubmit(data) {
      this.submitLoading = true
      api.saveOrUpdate(data).then(() => {
        this.listData()
        // 重置formData
        this.formData = {}
        this.dialogVisible = false
        this.submitLoading = false
      })
    },
    getUserStatus() {
      return api.userStatus()
    },
    getSex() {
      return api.sex()
    },
    setUserStatus() {
      this.getUserStatus().then(res => {
        const data = res.data
        this.tableForm.items[2].itemRender.options = mappingArray({ value: 'label', code: 'value' }, data)
        this.formDesc.status.options = mappingArray({ value: 'text', code: 'value' }, data)
      })
    },
    setSex() {
      this.getSex().then(res => {
        const data = res.data
        this.tableForm.items[3].itemRender.options = mappingArray({ value: 'label', code: 'value' }, data)
        this.formDesc.sex.options = mappingArray({ value: 'text', code: 'value' }, data)
      })
    },
    getRoles() {
      roleApi.query().then(res => {
        this.formDesc.roleIds.options = mappingArray({ name: 'text', id: 'value' }, res.data)
      }
      )
    },
    resetCloseDialog() {
      this.resetPasswordDialogVisible = false
      this.resetFormData = {}
    },
    resetPassword(row) {
      this.resetPasswordDialogVisible = true
      this.resetTips = `请输入"${row.userName}"的新密码`
      this.resetFormData.id = row.id
    },
    resetPasswordSubmit() {
      this.resetSubmitLoading = true
      api.resetPassword(this.resetFormData).then(res => {
        this.resetSubmitLoading = false
        this.resetCloseDialog()
      }, () => { this.resetSubmitLoading = false })
    }

  }
}
</script>
<style lang="sass" scoped>
.resetTips
  display: block
  padding: 10px 0
</style>
